﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Common;

namespace Service.Interface
{
    public class GenericClientProxy<T> : System.ServiceModel.ClientBase<T>, IDisposable where T : class
    {
        T _serviceInstance;

        public GenericClientProxy(string endpointname)
            : base(endpointname)
        {

        }
        public T Proxy
        {
            get
            {
                if (_serviceInstance != null
                                && (
                                    ((IChannel)_serviceInstance).State == CommunicationState.Faulted
                                || ((IChannel)_serviceInstance).State == CommunicationState.Closed)
                  )
                {
                    ((IChannel)_serviceInstance).Abort();
                    _serviceInstance = null;
                }

                if (_serviceInstance == null)
                {
                   
                    _serviceInstance = this.ChannelFactory.CreateChannel();
                }
                return _serviceInstance;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this.State == CommunicationState.Faulted)
            {
                base.Abort();
            }
            else
            {
                try
                {
                    base.Close();
                }
                catch
                {
                    base.Abort();
                }
            }
        }

        #endregion
    }
}
